package com.kylin.common.util;

import java.util.Enumeration;
import java.util.List;
import java.util.Locale;

import org.apache.log4j.Logger;

import com.kylin.common.dict.orm.Dict;
import com.kylin.common.exception.BusinessException;
import com.kylin.common.exception.SystemException;

public class UTool {

	static Logger log = Logger.getLogger(UTool.class);
	/**
	 * 翻译语言名称，输入语言代码和本地化对象，返回本地化的语言名称
	 * @param language
	 * @param locale
	 * @return
	 * @throws NumberFormatException
	 * @throws BusinessException
	 */
	static public String getLanguageName(String language, Locale locale)
			throws NumberFormatException, BusinessException {
		if(language == null || language.equals(""))
			return null;
		Locale theLocale = getLocaleByLang(language);
		if(locale == null)
			locale = Locale.getDefault();	
		return theLocale.getDisplayLanguage(locale);
	}

	/**
	 * 翻译国家名称，输入国家代码和本地化对象，返回本地化的国家名称
	 * @param country
	 * @param locale
	 * @return
	 * @throws NumberFormatException
	 * @throws BusinessException
	 */
	static public String getCountryName(String country, Locale locale)
			throws NumberFormatException, BusinessException {
		if(country == null)
			return "";
		Locale theLocale = getLocaleByLang(country);
		if(theLocale == null)
			return "";
		if(locale != null)
			return theLocale.getDisplayCountry(locale);
		else
			return theLocale.getDisplayCountry();
	}

	
	/**
	 * 翻译字典选项名称，输入字典项的值，返回字典项的显示名称
	 * @param optionId
	 * @return
	 * @throws BusinessException
	 */
	static public String getDictOptionName(String optionId)
			throws BusinessException {
		Enumeration enu = MemObjFactory.DictMap.keys();
		while(enu.hasMoreElements()){
			String key = (String) enu.nextElement();
			List list = (List) MemObjFactory.DictMap.get(key);
			for(int i=0;i< list.size();i++){
				Dict d = (Dict)list.get(i);
				if(d.getId().toString().equals(optionId))
					return d.getName();
			}
		}
		return "";
	}

	/**
	 * 根据语言或国家代码 获得一个本地化对象
	 * @param language  语言或国家代码
	 * @return
	 */
	static public Locale getLocaleByLang(String language) {
		if (language == null || language.equals(""))
			throw new SystemException("语言或国家名称不能为 null，参见 ISO639");
		String[] subs = language.split("_");
		if (subs.length == 3)
			return new Locale(subs[0], subs[1], subs[2]);
		else if (subs.length == 2)
			return new Locale(subs[0], subs[1]);
		else
			return new Locale(language);
	}

	static public void sendSystemMail(String toAddress,String subject,String content,String []paraValues) throws BusinessException{
		if(paraValues != null){
			for(int i=0;i<paraValues.length;i++){
				if(paraValues[i] == null )
					continue;
				content =content.replaceAll("\\{"+i+"\\}", paraValues[i]);
			}
		}
		SendMailBean sender = new SendMailBean();
    	sender.send(toAddress, subject, content) ;
		
	}

	/**
	 * 发送 html 格式的邮件
	 * @param toAddress  收件人
	 * @param subject    邮件标题
	 * @param content    邮件内容
	 * @param paraValues 邮件内容中的替换变量
	 * @return  返回邮件的内容
	 * @throws BusinessException
	 */
	static public String sendHtmlSystemMail(String toAddress,String subject,String content,String []paraValues) throws BusinessException{
System.out.println("paraValues="+paraValues);
		log.debug("发送 html 格式的邮件:"+toAddress+","+subject);
		if(paraValues != null){
			for(int i=0;i<paraValues.length;i++){
				if(paraValues[i] == null )
					continue;
				log.debug("邮件paraValues[i]="+paraValues[i]);
				content =content.replaceAll("\\{"+i+"\\}", paraValues[i]);
			}
		}
		log.debug("邮件content="+content);
		SendMailBean sender = new SendMailBean();
		sender.setContentType("text/html");
    	sender.send(toAddress, subject, content) ;
		return content;
	}

	/**
	 * 发送激活用户（公司用户）的通知邮件
	 * 系统按预设的模版文件样式向客户发出邮件通知
	 * 在模版文件里的变量，模版中定义为类似： 欢迎你{0}，你的密码是 {1}
	 * @param userName
	 * @param password
	 * @param email
	 * @return
	 * @throws BusinessException
	 */
	public static String sendActivationMail(String userName,String password,String email,String language) 
		throws BusinessException{
 		String templetContent = FileOperater.getActivationMailFileContent(language);
 		int index = templetContent.indexOf("\n");
 		String subject = templetContent.substring(0,index);
 		String content = templetContent.substring(index,templetContent.length()); 		
 		// 在模版文件里的变量，模版中定义为类似： 欢迎你{0}，你的密码是 {1}
 		String[] paraValues= new String[]{ userName, password };
 		content = UTool.sendHtmlSystemMail(email, subject, content, paraValues );
 		return content;
		
	}
	

	/**
	 * 发送密码找回的通知邮件
	 * 系统按预设的模版文件样式向客户发出带有用户密码的邮件
	 * @param userName
	 * @param password
	 * @param email
	 * @return
	 * @throws BusinessException
	 */
	public static String sendGetPasswordMail(String userName,String password,String email,String language) 
		throws BusinessException{
 		String templetContent = FileOperater.getSendPasswordMailFileContent(language);
 		int index = templetContent.indexOf("\n");
 		String subject = templetContent.substring(0,index);
 		String content = templetContent.substring(index,templetContent.length()); 		
 		// 在模版文件里的变量，模版中定义为类似：  你丢失的密码是 {0},请尽快登录修改你的密码
 		String[] paraValues= new String[]{ userName, password };
 		content = UTool.sendHtmlSystemMail(email, subject, content, paraValues );
 		return content;
		
	}
	
	public static void main(String[]s){
		String content="testsetset{0},dfthq{1} dggfghhhh{2}.....{3}vvvvvvv{4}";
		String[] paraValues= new String[]{
	 			"好不错",
	 			"0000",
	 			"###"
	 		};
		if(paraValues != null){
			for(int i=0;i<paraValues.length;i++){
				if(paraValues[i] == null )
					continue;
				String regx = "\\{"+(i)+"\\}";
				System.out.print("\nreplace "+regx +" -by-"+paraValues[i]);
				content =content.replaceAll(regx, paraValues[i]);
			}
		}
		System.out.println("\ncont="+content);
	}
}
